<!-- 添加二维码logo，将logo绘制到二维码中间，下载含有logo的二维码 -->
<template>
  <div class="qrcode-box">
    <!--内链文档（在项目内展示<即嵌入页面>）
     <iframe src="https://juejin.cn/post/7228990409909108793" frameborder="0" /> -->
    <el-button @click="dialogVisible = true">生成二维码</el-button>
    <el-dialog
      title="二维码"
      :visible.sync="dialogVisible"
      @opened="generateQRCode"
    >
      <!-- 二维码主要部分 -->
      <canvas id="canvas" ref="qrCanvas" title="二维码"></canvas>
      <!-- logo 用定位定到二维码中间的 -->
      <div class="card-logo" :style="logoStyle"></div>
      <div class="qrcodeDownload">
        <i class="el-icon-download" @click="downLoadQrcode"></i>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import QRCode from "qrcode"; //引入生成二维码插件
export default {
  name: "qrcode",
  data () {
    return {
      dialogVisible: false,
      logoStyle: {}, // 用于动态设置 Logo 的位置
    }
  },
  props: {
    canvasWidth: {//画布的宽度
      default: 97,
      type: Number,
    },
    canvasHeight: {//画布的高度
      default: 97,
      type: Number,
    },
    url: {//生成二维码的地址
      default: "http://192.168.2.125:8888/1/labels",
      // type: String,
      // required: true,//出现Missing required prop: "url"错误，解决方案：去掉required: true
    },
    logoUrl: {//logo图片地址
      default: "https://img0.baidu.com/it/u=4096841107,3844863894&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800",
      type: String,
    }
  },



  methods: {
    // 生成的二维码宽高小于100的时候会读取不到信息，生成的二维码信息不够齐全，模糊
    generateQRCode () {
      let opts = {
        errorCorrectionLevel: "M", //4个容错级别（L:7%, M: 15%, Q: 25%, H: 30%）,指二维码被遮挡可以扫出结果的区域比例
        type: "image/png", //生成的二维码类型
        quality: 0.3,
        margin: 2, //二维码留白边距
        width: this.canvasWidth, //宽
        height: this.canvasHeight, //高
        text: "内容", //二维码内容
        color: {
          light: "#ffffff", //背景色
        },
      };
      // 将获取到的数据（val）画到msg（canvas）上,加上时间戳动态生成二维码
      const canvas = this.$refs.qrCanvas;
      const ctx = canvas.getContext('2d');

      canvas.width = this.canvasWidth;
      canvas.height = this.canvasHeight;
      QRCode.toCanvas(canvas, this.url, opts, (error) => {
        if (error) console.error(error);
        this.drawLogo(ctx);//调用绘制logo到二维码上的方法
      });
    },
    /**将logo绘制到二维码上*/
    drawLogo (ctx) {
      const logourl = this.logoUrl;
      const img = new Image();
      // img.src = require('@/assets/images/user.png');//logo图片
      img.src = logourl;
      img.onload = () => {
        const logoSize = 20; // Logo 的大小
        const qrCodeSize = Math.min(this.canvasWidth, this.canvasHeight); // 获取二维码的最小边长
        const padding = (qrCodeSize - logoSize) / 2; // 计算 Logo 的位置

        // 将 Logo 绘制到二维码中心
        ctx.drawImage(img, padding, padding, logoSize, logoSize);
        this.logoStyle = {
          top: `${padding}px`,
          left: `${padding}px`,
          width: `${logoSize}px`,
          height: `${logoSize}px`,
        };
      };
    },

    //下载含有logo二维码
    downLoadQrcode () {
      const canvas = this.$refs.qrCanvas;
      const imgSrc = canvas.toDataURL('image/png');
      const alink = document.createElement('a');
      alink.href = imgSrc;
      alink.download = 'qrcode_with_logo.png';
      alink.click();
    },


  }
};
</script>
<style lang="scss" scoped>
i {
  float: right;
}
.qrcode-box {
  position: relative;

  .card-logo {
    width: 20px;
    height: 20px;
    position: absolute;
    top: 34px;
    left: 34px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>









<!-- 扫描二维码跳转到链接 -->
<!-- <template>
  <div id="qrCode" @click="refreshQrCode">
    <div id="code"></div>
    <canvas id="canvas"></canvas>
  </div>
</template>

<script>
import QRCode from 'qrcode'
export default {
  data () {
    return {
      msg: 'hello vue',
      codes: '',
    }
  },

  components: {
    QRCode: QRCode
  },

  methods: {
    useqrcode () {
      const canvas = document.getElementById('canvas');
      // const ctx = canvas.getContext('2d');
      // ctx.clearRect(0, 0, canvas.width, canvas.height);
      QRCode.toCanvas(canvas, 'http://192.168.2.125:8888/1/labels', {
        margin: 1,
        color: {
          dark: '#000000', // 黑色
          light: '#f1f0ec' // 白色
        }
      }, (error) => {
        if (error) console.error(error);
        console.log('QRCode success!');
      });

    },
    refreshQrCode () {
      this.useqrcode();
    }
  },

  mounted () {
    this.useqrcode();
  }
}
</script> -->
